package com.hotely5d.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hotely5d.dao.MemberMapper;
import com.hotely5d.dao.OrdersMapper;
import com.hotely5d.dao.RoomMapper;
import com.hotely5d.entity.Member;
import com.hotely5d.entity.Orders;
import com.hotely5d.entity.Room;
import com.hotely5d.entity.model.Result;
import com.hotely5d.entity.model.StatusCode;
import com.hotely5d.entity.query.OrderQuery;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RoomService roomService;
    @Autowired
    private MemberMapper memberMapper;

    public List<Orders> findAll() {
        // 只查询未删除的订单
        return ordersMapper.selectList(new EntityWrapper<Orders>().eq("deleted", 0));
    }

    public Page<Orders> search(Page<Orders> page,Orders orders) {
        List<Orders> list = ordersMapper.selectPage(page, getEntityWrapper(orders));
        for (Orders o : list) {
            Room room = roomService.findById(o.getRoomId());
            Member member = memberMapper.selectById(o.getMemberId());
            o.setRoom(room);
            o.setMember(member);
        }
        return page.setRecords(list);
    }

    public List<Orders> search(Orders orders) {
        return ordersMapper.selectList(getEntityWrapper(orders));
    }

    //条件构造器
    private EntityWrapper<Orders> getEntityWrapper(Orders orders){
        EntityWrapper<Orders> entityWrapper = new EntityWrapper<>();
        // 只查询未删除的订单
        entityWrapper.eq("deleted", 0);
        if(null != orders){
            if(!StringUtils.isEmpty(orders.getRemark())){
                entityWrapper.like("remark",String.valueOf(orders.getRemark()));
            }
            if (!StringUtils.isEmpty(orders.getMemberId())) {
                entityWrapper.eq("member_id", String.valueOf(orders.getMemberId()));
            }
            if (!StringUtils.isEmpty(orders.getStatus())) {
                entityWrapper.eq("status", String.valueOf(orders.getStatus()));
            }
        }
        entityWrapper.orderBy("id",false);
        return entityWrapper;
    }

    public void modify(Orders orders) {
        ordersMapper.updateById(orders);
    }

    public Result add(OrderQuery orderQuery) {
        Orders orders = new Orders();
        //判断用户是否存在，不存在则创建（只查询未删除的用户）
        List<Member> memberList = memberMapper.selectList(new EntityWrapper<Member>()
                .eq("idcard",orderQuery.getIdcard())
                .eq("deleted", 0));
        if (memberList.size() != 0){
            orders.setMemberId(memberList.get(0).getId());
        }else{
            Member member = new Member();
            member.setCreateTime(new Date());
            member.setGender(orderQuery.getGender());
            member.setIdcard(orderQuery.getIdcard());
            member.setName(orderQuery.getName());
            member.setPhone(orderQuery.getPhone());
            member.setUsername(orderQuery.getPhone());
            member.setPassword("123456");//初始化密码
            // 设置默认值：未删除
            member.setDeleted(0);
            memberMapper.insert(member);
            orders.setMemberId(member.getId());
        }
        Room room = roomService.findById(orderQuery.getRoomId());
        orders.setStartTime(new Date());
        orders.setDays(orderQuery.getDays());
        orders.setRoomId(orderQuery.getRoomId());
        orders.setStatus(2);
        orders.setMoney(room.getCategory().getPrice());
        // 设置默认值：未删除
        orders.setDeleted(0);
        ordersMapper.insert(orders);
        return new Result(true, StatusCode.OK,"操作成功");
    }

    public Orders findById(Integer id) {
        // 只查询未删除的订单
        List<Orders> ordersList = ordersMapper.selectList(new EntityWrapper<Orders>().eq("id", id).eq("deleted", 0));
        return ordersList.isEmpty() ? null : ordersList.get(0);
    }

    public void removeById(Integer id) {
        // 实现逻辑删除：将deleted字段设置为1
        Orders orders = new Orders();
        orders.setId(id);
        orders.setDeleted(1);
        ordersMapper.updateById(orders);
    }

    /**
     * 导出入住数据到Excel
     */
    public void exportOrdersData(Orders orders, HttpServletResponse response) throws IOException {
        // 查询数据
        List<Orders> ordersList = ordersMapper.selectList(getEntityWrapper(orders));

        // 填充关联数据
        for (Orders o : ordersList) {
            Room room = roomService.findById(o.getRoomId());
            Member member = memberMapper.selectById(o.getMemberId());
            o.setRoom(room);
            o.setMember(member);
        }

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("入住信息");

        // 创建标题样式
        CellStyle titleStyle = workbook.createCellStyle();
        Font titleFont = workbook.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 14);
        titleStyle.setFont(titleFont);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);

        // 创建数据样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);

        // 创建日期样式
        CellStyle dateStyle = workbook.createCellStyle();
        dateStyle.cloneStyleFrom(dataStyle);
        CreationHelper createHelper = workbook.getCreationHelper();
        dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"订单ID", "用户姓名", "用户电话", "身份证号", "性别", "房间号", "房型", "房间价格",
                           "入住时间", "居住天数", "状态", "备注", "实付金额", "退房时间"};

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(titleStyle);
        }

        // 填充数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < ordersList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Orders order = ordersList.get(i);

            // 订单ID
            Cell cell0 = row.createCell(0);
            cell0.setCellValue(order.getId());
            cell0.setCellStyle(dataStyle);

            // 用户姓名
            Cell cell1 = row.createCell(1);
            cell1.setCellValue(order.getMember() != null ? order.getMember().getName() : "");
            cell1.setCellStyle(dataStyle);

            // 用户电话
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(order.getMember() != null ? order.getMember().getPhone() : "");
            cell2.setCellStyle(dataStyle);

            // 身份证号
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(order.getMember() != null ? order.getMember().getIdcard() : "");
            cell3.setCellStyle(dataStyle);

            // 性别
            Cell cell4 = row.createCell(4);
            if (order.getMember() != null && order.getMember().getGender() != null) {
                cell4.setCellValue(order.getMember().getGender() == 1 ? "男" : "女");
            } else {
                cell4.setCellValue("");
            }
            cell4.setCellStyle(dataStyle);

            // 房间号
            Cell cell5 = row.createCell(5);
            cell5.setCellValue(order.getRoom() != null && order.getRoom().getRoomNum() != null ?
                              order.getRoom().getRoomNum().toString() : "");
            cell5.setCellStyle(dataStyle);

            // 房型
            Cell cell6 = row.createCell(6);
            cell6.setCellValue(order.getRoom() != null && order.getRoom().getCategory() != null ?
                              order.getRoom().getCategory().getCategoryName() : "");
            cell6.setCellStyle(dataStyle);

            // 房间价格
            Cell cell7 = row.createCell(7);
            if (order.getRoom() != null && order.getRoom().getCategory() != null && order.getRoom().getCategory().getPrice() != null) {
                cell7.setCellValue(order.getRoom().getCategory().getPrice().doubleValue());
            } else {
                cell7.setCellValue("");
            }
            cell7.setCellStyle(dataStyle);

            // 入住时间
            Cell cell8 = row.createCell(8);
            if (order.getStartTime() != null) {
                cell8.setCellValue(order.getStartTime());
                cell8.setCellStyle(dateStyle);
            } else {
                cell8.setCellValue("");
                cell8.setCellStyle(dataStyle);
            }

            // 居住天数
            Cell cell9 = row.createCell(9);
            cell9.setCellValue(order.getDays() != null ? order.getDays() : 0);
            cell9.setCellStyle(dataStyle);

            // 状态
            Cell cell10 = row.createCell(10);
            String statusText = "";
            if (order.getStatus() != null) {
                switch (order.getStatus()) {
                    case 1: statusText = "已预订"; break;
                    case 2: statusText = "已入住"; break;
                    case 3: statusText = "已退房"; break;
                    default: statusText = "未知"; break;
                }
            }
            cell10.setCellValue(statusText);
            cell10.setCellStyle(dataStyle);

            // 备注
            Cell cell11 = row.createCell(11);
            cell11.setCellValue(order.getRemark() != null ? order.getRemark() : "");
            cell11.setCellStyle(dataStyle);

            // 实付金额
            Cell cell12 = row.createCell(12);
            if (order.getMoney() != null && order.getDays() != null) {
                cell12.setCellValue(order.getMoney().doubleValue() * order.getDays());
            } else {
                cell12.setCellValue("");
            }
            cell12.setCellStyle(dataStyle);

            // 退房时间
            Cell cell13 = row.createCell(13);
            if (order.getCheckOutTime() != null) {
                cell13.setCellValue(order.getCheckOutTime());
                cell13.setCellStyle(dateStyle);
            } else {
                cell13.setCellValue("");
                cell13.setCellStyle(dataStyle);
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
            // 设置最小列宽
            int currentWidth = sheet.getColumnWidth(i);
            if (currentWidth < 3000) {
                sheet.setColumnWidth(i, 3000);
            }
            // 设置最大列宽
            if (currentWidth > 8000) {
                sheet.setColumnWidth(i, 8000);
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = "入住信息_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 写入响应
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
